<template>
    <div class="fabu-container">
        <h2 class="title">发布作业</h2>
        <div class="form-wrapper">
            <el-form :model="homeworkForm" :rules="rules" ref="homeworkForm">
                <!-- 所有表单项使用统一的 form-item 和 form-label 结构 -->
                <div class="form-item">
                    <div class="form-label">作业名称</div>
                    <el-input 
                        v-model="homeworkForm.homeworkName" 
                        placeholder="请输入作业名称">
                    </el-input>
                </div>

                <div class="form-item">
                    <div class="form-label">课程名称</div>
                    <el-select 
                        v-model="homeworkForm.courseclass" 
                        placeholder="请选择课程">
                        <el-option
                            v-for="item in courseOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>

                <div class="form-item">
                    <div class="form-label">作业描述</div>
                    <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入作业描述"
                        v-model="homeworkForm.description"
                        class="description-input">
                    </el-input>
                </div>

                <div class="form-item">
                    <div class="form-label">开始时间</div>
                    <el-date-picker
                        v-model="homeworkForm.start"
                        type="datetime"
                        placeholder="选择开始时间"
                        :editable="false"
                        :clearable="false">
                    </el-date-picker>
                </div>

                <div class="form-item">
                    <div class="form-label">截止时间</div>
                    <el-date-picker
                        v-model="homeworkForm.end"
                        type="datetime"
                        placeholder="选择截止时间"
                        :editable="false"
                        :clearable="false">
                    </el-date-picker>
                </div>

                <div class="form-item">
                    <div class="form-label">分数</div>
                    <el-input-number 
                        v-model="homeworkForm.score" 
                        :min="0" 
                        :max="100"
                        class="score-input">
                    </el-input-number>
                </div>

                <el-form-item label="作业附件" prop="fileUrl">
                    <el-upload
                        class="homework-uploader"
                        action="http://localhost:9999/file/upload"
                        :show-file-list="true"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :before-upload="beforeUpload"
                        name="file"
                        :data="uploadData"
                        :headers="headers"
                    >
                        <el-button type="primary">
                            <el-icon><Upload /></el-icon> 点击上传
                        </el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持任意文件格式，单个文件不超过10MB
                            </div>
                        </template>
                    </el-upload>
                    <!-- 显示已上传的文件 -->
                    <div v-if="homeworkForm.fileUrl" class="file-list">
                        <div class="file-item">
                            <el-link 
                                :href="`http://localhost:9999/file/${homeworkForm.fileUrl}`" 
                                type="primary" 
                                target="_blank"
                            >
                                查看已上传文件
                            </el-link>
                        </div>
                    </div>
                </el-form-item>

                <div class="form-item button-group">
                    <el-button type="primary" @click="submitForm('homeworkForm')">发布作业</el-button>
                    <el-button @click="resetForm('homeworkForm')">重置</el-button>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    name: 'HomeworkFabu',
    data() {
        return {
            courseOptions: [],
            homeworkForm: {
                homeworkName: '',
                courseclass: '',
                description: '',
                start: new Date(),
                end: new Date(),
                score: 100,
                teacherId: '',
                teateacherName: '',
                administratorId: 0,
                state: '进行中',
                image: '',
                fileUrl: ''
            },
            headers: {
                // 移除 Content-Type，让浏览器自动设置
            },
            uploadData: {
                // 如果需要额外的参数可以在这里添加
            },
            rules: {
                homeworkName: [
                    { required: true, message: '请输入作业名称', trigger: 'blur' },
                    { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                ],
                courseclass: [
                    { required: true, message: '请选择课程班级', trigger: 'change' }
                ],
                description: [
                    { required: true, message: '请输入作业描述', trigger: 'blur' }
                ],
                start: [
                    { type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
                ],
                end: [
                    { type: 'date', required: true, message: '请选择结束时间', trigger: 'change' }
                ],
                score: [
                    { required: true, message: '请输入分数', trigger: 'blur' },
                    { type: 'number', message: '分数必须为数字' }
                ],
                image: [
                    { required: false, message: '请上传作业图片', trigger: 'change' }
                ],
                fileUrl: [
                    { required: false, message: '请上传作业附件', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.getTeacherCourses();
        
        const teacherInfo = JSON.parse(localStorage.getItem('users') || '{}');
        this.homeworkForm.teacherId = teacherInfo.userId || '';
        this.homeworkForm.teateacherName = teacherInfo.userName || '';
    },
    methods: {
        formatDate(date) {
            if (!date) return null;
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            const hours = String(d.getHours()).padStart(2, '0');
            const minutes = String(d.getMinutes()).padStart(2, '0');
            const seconds = String(d.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
        },

        async submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    try {
                        const teacherInfo = JSON.parse(localStorage.getItem('users') || '{}');
                        console.log('教师信息:', teacherInfo);

                        const requestData = {
                            homeworkName: this.homeworkForm.homeworkName,
                            courseclass: this.homeworkForm.courseclass,
                            description: this.homeworkForm.description,
                            start: this.formatDate(this.homeworkForm.start),
                            end: this.formatDate(this.homeworkForm.end),
                            score: this.homeworkForm.score,
                            teacherId: teacherInfo.userId,
                            teateacherName: teacherInfo.userName,
                            administratorId: 0,
                            state: '进行中',
                            fileUrl: this.homeworkForm.fileUrl
                        };

                        console.log('发送的数据:', JSON.stringify(requestData, null, 2));

                        const response = await axios.post('http://localhost:9999/homework/addHomework', requestData);
                        
                        console.log('服务器响应:', response.data);

                        if (response.data === true) {
                            this.$message.success('作业发布成功！');
                            this.$router.push('/layout/homework');
                        } else {
                            this.$message.error('作业发布失败');
                        }
                    } catch (error) {
                        console.error('发布作业失败:', error);
                        this.$message.error('发布作业失败：' + (error.message || '未知错误'));
                    }
                } else {
                    this.$message.error('请填写完整信息');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.fileList = [];
        },
        async getTeacherCourses() {
            try {
                const userInfo = JSON.parse(localStorage.getItem('users'));
                if (!userInfo || !userInfo.userId) {
                    this.$message.error('未找到用户信息，请重新登录');
                    return;
                }

                const response = await axios.post('http://localhost:9999/teach/getTeach', 
                    userInfo,
                    {
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8'
                        }
                    }
                );

                if (!response.data) {
                    this.$message.info('未获取到课程数据');
                    return;
                }

                this.courseOptions = response.data.map(course => ({
                    value: course.courseclassT,
                    label: course.courseclassT
                }));

            } catch (error) {
                console.error('获取教师课程失败:', error);
                this.$message.error('获取课程列表失败');
            }
        },
        handleUploadSuccess(response) {
            console.log('上传响应:', response);
            this.homeworkForm.fileUrl = response.data;
        },
        handleUploadError(error) {
            console.error('上传错误:', error);
            this.$message.error('文件上传失败，请重试');
        },
        beforeUpload(file) {
            const maxSize = 10 * 1024 * 1024; // 10MB
            if (file.size > maxSize) {
                this.$message.error('文件大小不能超过 10MB!');
                return false;
            }
            return true;
        }
    }
};
</script>

<style lang="less" scoped>
.fabu-container {
    padding: 20px;
    background-color: #fff;
    width: 800px;
    margin: 60px auto;

    .title {
        text-align: center;
        margin-bottom: 30px;
        font-size: 20px;
        color: #303133;
    }

    .form-wrapper {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
    }

    .form-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 22px;
        position: relative;

        .form-label {
            width: 70px;
            line-height: 32px;
            padding-right: 12px;
            color: #606266;
            font-size: 14px;
            text-align: justify;
            text-align-last: justify;
            
            &::after {
                content: "：";  
                position: absolute;
                right: -12px;
            }
        }

        .el-input,
        .el-select,
        .el-date-picker,
        .score-input,
        .upload-demo,
        .description-input {
            margin-left: 20px;
            width: calc(100% - 90px);
        }

        .score-input {
            width: 130px;
        }

        .description-input {
            /deep/ .el-textarea__inner {
                min-height: 100px;
            }
        }

        &.button-group {
            padding-left: 90px;
            margin-top: 30px;
        }
    }
}

// 响应式设计
@media screen and (max-width: 768px) {
    .fabu-container {
        .form-item {
            flex-direction: column;
            
            .form-label {
                width: auto;
                text-align: left;
                margin-bottom: 8px;
                
                &::after {
                    position: static;
                    margin-left: 2px;
                }
            }

            .el-input,
            .el-select,
            .el-date-picker,
            .score-input,
            .upload-demo,
            .description-input {
                margin-left: 0;
                width: 100%;
            }

            &.button-group {
                padding-left: 0;
                display: flex;
                justify-content: center;
            }
        }
    }
}

.homework-uploader {
    .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;
        
        &:hover {
            border-color: #409EFF;
        }
    }

    .el-upload__tip {
        font-size: 12px;
        color: #606266;
        margin-top: 7px;
    }
}

/* 预览图片样式 */
.image-preview {
    width: 100%;
    max-width: 200px;
    height: auto;
    margin-top: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 上传按钮样式 */
:deep(.el-upload-list) {
    margin-top: 10px;
}

:deep(.el-button) {
    margin-right: 10px;
}

/* 提示文字样式 */
:deep(.el-upload__tip) {
    line-height: 1.2;
    padding: 8px 0;
    color: #909399;
}

.file-list {
    margin-top: 10px;
    
    .file-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .el-link {
            margin-right: 10px;
        }
    }
}

</style>